import zipfile
import string
from urllib3 import PoolManager

def create_proxy_auth_extension(proxy_host, proxy_port,
                               proxy_username, proxy_password,
                               scheme='http', plugin_path=None):
    if plugin_path is None:
        # 请保证下面的路径可用。说明：
        # 1、这个 zip 文件不需要存在，程序自动生成；
        # 2、这个文件是 Chrome 的扩展文件，用于配置代理；
        # 3、如果您是 Windows 系统，请修改为：C:\\qtproxy-tunnel-ext.zip，或者其他存在的路径
        plugin_path =  r'C:\\Users\\zhouyu\\Desktop\\scihub\\qtproxy-tunnel-ext.zip'

    manifest_json = """
    {
        "version": "1.0.1",
        "manifest_version": 2,
        "name": "Qtproxy(proxy.horocn.com)",
        "permissions": [
            "proxy",
            "tabs",
            "unlimitedStorage",
            "storage",
            "<all_urls>",
            "webRequest",
            "webRequestBlocking"
        ],
        "background": {
            "scripts": ["background.js"]
        },
        "minimum_chrome_version":"22.0.0"
    }
    """

    background_js = string.Template(
        """
        var config = {
            mode: "fixed_servers",
            rules: {
                singleProxy: {
                    scheme: "${scheme}",
                    host: "${host}",
                    port: parseInt(${port})
                },
                bypassList: ["localhost"]
            }
          };

        chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

        function callbackFn(details) {
            return {
                authCredentials: {
                    username: "${username}",
                    password: "${password}"
                }
            };
        }

        chrome.webRequest.onAuthRequired.addListener(
                    callbackFn,
                    {urls: ["<all_urls>"]},
                    ['blocking']
        );
        """
    ).substitute(
        host=proxy_host,
        port=proxy_port,
        username=proxy_username,
        password=proxy_password,
        scheme=scheme,
    )

    with zipfile.ZipFile(plugin_path, 'w') as zp:
        zp.writestr("manifest.json", manifest_json)
        zp.writestr("background.js", background_js)

    return plugin_path

tunnelHost = "a901.kdltps.com"
tunnelPort = "15818"
username = "t19744135387372"
password = "gx1874ki"

proxy_auth_plugin_path = create_proxy_auth_extension(
    proxy_host=tunnelHost,
    proxy_port=tunnelPort,
    proxy_username=username,
    proxy_password=password)


